package cn.woochen.comlib.span

import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.View
import android.widget.TextView

/**
 *类描述：颜色可变的文本带点击事件(场景：用户协议)
 *@author woochen
 *@time 2021/8/24 10:42
 */
object SpanUtil {

    fun transStr(textView: TextView,original:String,vararg spanBeans:SpanBean):SpannableString{
        textView.highlightColor = Color.parseColor("#00000000")//取消点击事件的背景色
        textView.movementMethod = LinkMovementMethod.getInstance()//增加点击事件
        val spannableString = SpannableString(original)
        spanBeans.forEach {
            val startIndex = original.indexOf(it.targetText)
            val endIndex = startIndex + it.targetText.length
            spannableString.setSpan(ForegroundColorSpan(it.color), startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
            spannableString.setSpan(object : ClickableSpan() {

                override fun updateDrawState(ds: TextPaint) {
                    ds.isUnderlineText = false
                }

                override fun onClick(widget: View) {
                    it.clickBlock.invoke()
                }
            }, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
        }
        return spannableString
    }
}